<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="出货单号" prop="outboundOrderNo">
        <el-input
          v-model="queryParams.outboundOrderNo"
          placeholder="请输入出货单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="药品名称" prop="drugName">
        <el-input
          v-model="queryParams.drugName"
          placeholder="请输入药品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出货日期" prop="outboundDate">
        <el-date-picker
          v-model="queryParams.outboundDate"
          type="date"
          placeholder="选择出货日期"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['veterinary:outbound:add']"
        >新增出货</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['veterinary:outbound:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['veterinary:outbound:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['veterinary:outbound:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="outboundList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="出货单号" align="center" prop="outboundOrderNo" />
      <el-table-column label="客户名称" align="center" prop="customerName" :show-overflow-tooltip="true" />
      <el-table-column label="药品名称" align="center" prop="drugName" :show-overflow-tooltip="true" />
      <el-table-column label="规格" align="center" prop="drugSpecification" />
      <el-table-column label="兽药批号" align="center" prop="batchNumber" />
      <el-table-column label="数量" align="center" prop="quantity" />
      <el-table-column label="单价" align="center" prop="unitPrice">
        <template slot-scope="scope">
          <span>¥{{ parseFloat(scope.row.unitPrice).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="金额" align="center" prop="totalAmount">
        <template slot-scope="scope">
          <span>¥{{ parseFloat(scope.row.totalAmount).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="出货日期" align="center" prop="outboundDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.outboundDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="休药期" align="center" prop="withdrawalPeriod">
        <template slot-scope="scope">
          <span class="text-warning">{{ scope.row.withdrawalPeriod }}天</span>
        </template>
      </el-table-column>
      <el-table-column label="经办人" align="center" prop="operator" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['veterinary:outbound:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['veterinary:outbound:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改出货管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="出货单号" prop="outboundOrderNo">
              <el-input v-model="form.outboundOrderNo" placeholder="系统自动生成" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户" prop="customerId">
              <el-select v-model="form.customerId" placeholder="请选择客户" filterable @change="handleCustomerChange">
                <el-option
                  v-for="customer in customerList"
                  :key="customer.customerId"
                  :label="customer.customerName"
                  :value="customer.customerId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="药品" prop="inventoryId">
              <el-select v-model="form.inventoryId" placeholder="请选择药品" filterable @change="handleInventoryChange">
                <el-option
                  v-for="inventory in inventoryList"
                  :key="inventory.inventoryId"
                  :label="`${inventory.drugName} (${inventory.drugSpecification}) - 库存:${inventory.quantity}`"
                  :value="inventory.inventoryId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="quantity">
              <el-input-number v-model="form.quantity" :min="1" :max="maxQuantity" placeholder="请输入数量" @change="calculateAmount" />
              <span v-if="maxQuantity > 0" class="text-info">（库存：{{ maxQuantity }}）</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="单价" prop="unitPrice">
              <el-input-number v-model="form.unitPrice" :precision="2" :step="0.01" :min="0" placeholder="请输入单价" @change="calculateAmount" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="金额" prop="totalAmount">
              <el-input-number v-model="form.totalAmount" :precision="2" placeholder="自动计算" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="出货日期" prop="outboundDate">
              <el-date-picker
                v-model="form.outboundDate"
                type="date"
                placeholder="选择出货日期"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经办人" prop="operator">
              <el-input v-model="form.operator" placeholder="请输入经办人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="selectedInventory">
          <el-col :span="24">
            <el-alert
              :title="`休药期提醒：${selectedInventory.drugName} 休药期为 ${selectedInventory.withdrawalPeriod} 天`"
              type="warning"
              :closable="false">
            </el-alert>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOutbound, getOutbound, delOutbound, addOutbound, updateOutbound, generateOrderNo } from "@/api/veterinary/outbound";
import { listCustomer } from "@/api/veterinary/customer";
import { listInventory } from "@/api/veterinary/inventory";

export default {
  name: "Outbound",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出货管理表格数据
      outboundList: [],
      // 客户列表
      customerList: [],
      // 库存列表
      inventoryList: [],
      // 选中的库存信息
      selectedInventory: null,
      // 最大可出货数量
      maxQuantity: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        outboundOrderNo: null,
        customerId: null,
        customerName: null,
        outboundDate: null,
        drugName: null,
        drugSpecification: null,
        batchNumber: null,
        operator: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        customerId: [
          { required: true, message: "客户不能为空", trigger: "change" }
        ],
        inventoryId: [
          { required: true, message: "药品不能为空", trigger: "change" }
        ],
        quantity: [
          { required: true, message: "数量不能为空", trigger: "blur" }
        ],
        unitPrice: [
          { required: true, message: "单价不能为空", trigger: "blur" }
        ],
        outboundDate: [
          { required: true, message: "出货日期不能为空", trigger: "change" }
        ],
        operator: [
          { required: true, message: "经办人不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getCustomerList();
    this.getInventoryList();
  },
  methods: {
    /** 查询出货管理列表 */
    getList() {
      this.loading = true;
      listOutbound(this.queryParams).then(response => {
        this.outboundList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取客户列表 */
    getCustomerList() {
      listCustomer({}).then(response => {
        this.customerList = response.rows;
      });
    },
    /** 获取库存列表 */
    getInventoryList() {
      listInventory({}).then(response => {
        this.inventoryList = response.rows.filter(item => item.quantity > 0 && item.inventoryStatus === '正常');
      });
    },
    /** 客户选择变化 */
    handleCustomerChange(customerId) {
      const customer = this.customerList.find(item => item.customerId === customerId);
      if (customer) {
        this.form.customerName = customer.customerName;
      }
    },
    /** 库存选择变化 */
    handleInventoryChange(inventoryId) {
      const inventory = this.inventoryList.find(item => item.inventoryId === inventoryId);
      if (inventory) {
        this.selectedInventory = inventory;
        this.form.drugName = inventory.drugName;
        this.form.drugSpecification = inventory.drugSpecification;
        this.form.batchNumber = inventory.batchNumber;
        this.form.withdrawalPeriod = inventory.withdrawalPeriod;
        this.maxQuantity = inventory.quantity;
        // 设置建议单价（可以基于进价加成）
        if (!this.form.unitPrice) {
          this.form.unitPrice = inventory.purchasePrice * 1; // 20%加成
        }
        this.calculateAmount();
      }
    },
    /** 计算金额 */
    calculateAmount() {
      if (this.form.quantity && this.form.unitPrice) {
        this.form.totalAmount = this.form.quantity * this.form.unitPrice;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        outboundId: null,
        outboundOrderNo: null,
        customerId: null,
        customerName: null,
        outboundDate: null,
        drugName: null,
        drugSpecification: null,
        batchNumber: null,
        quantity: null,
        unitPrice: null,
        totalAmount: null,
        withdrawalPeriod: null,
        operator: null,
        inventoryId: null
      };
      this.selectedInventory = null;
      this.maxQuantity = 0;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.outboundId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 生成出货单号
      generateOrderNo().then(response => {
        this.form.outboundOrderNo = response.data;
        this.form.outboundDate = new Date().toISOString().split('T')[0];
        this.open = true;
        this.title = "添加出货信息";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const outboundId = row.outboundId || this.ids
      getOutbound(outboundId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改出货信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.outboundId != null) {
            updateOutbound(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOutbound(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.getInventoryList(); // 刷新库存列表
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const outboundIds = row.outboundId || this.ids;
      this.$modal.confirm('是否确认删除出货信息编号为"' + outboundIds + '"的数据项？').then(function() {
        return delOutbound(outboundIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('veterinary/outbound/export', {
        ...this.queryParams
      }, `outbound_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.text-warning {
  color: #e6a23c;
  font-weight: bold;
}
.text-info {
  color: #909399;
  font-size: 12px;
  margin-left: 8px;
}
</style>
